"""
阿里云百炼向量化服务
"""
import os
import logging
from typing import List, Union
from openai import OpenAI

from app.config import Settings

logger = logging.getLogger(__name__)
settings = Settings()


class EmbeddingService:
    """阿里云百炼向量化服务"""
    
    def __init__(self):
        self.client = OpenAI(
            api_key=settings.dashscope_api_key,
            base_url=settings.dashscope_base_url
        )
        self.model = "text-embedding-v4"
        self.dimensions = 1024  # text-embedding-v4默认维度
    
    async def create_embeddings(self, texts: Union[str, List[str]]) -> List[List[float]]:
        """
        创建文本向量
        
        Args:
            texts: 单个文本字符串或文本列表
            
        Returns:
            向量列表
        """
        try:
            # 确保输入是列表格式
            if isinstance(texts, str):
                texts = [texts]
            
            # 调用阿里云百炼API
            response = self.client.embeddings.create(
                model=self.model,
                input=texts,
                dimensions=self.dimensions,
                encoding_format="float"
            )
            
            # 提取向量数据
            embeddings = []
            for data in response.data:
                embeddings.append(data.embedding)
            
            logger.info(f"成功创建 {len(embeddings)} 个向量")
            return embeddings
            
        except Exception as e:
            logger.error(f"向量化失败: {str(e)}")
            raise Exception(f"向量化服务错误: {str(e)}")
    
    async def create_single_embedding(self, text: str) -> List[float]:
        """
        创建单个文本向量
        
        Args:
            text: 文本内容
            
        Returns:
            向量数组
        """
        embeddings = await self.create_embeddings(text)
        return embeddings[0]
    
    def chunk_text(self, text: str, max_length: int = 8000) -> List[str]:
        """
        将长文本分块处理
        
        Args:
            text: 输入文本
            max_length: 每块的最大长度
            
        Returns:
            文本块列表
        """
        if len(text) <= max_length:
            return [text]
        
        chunks = []
        start = 0
        
        while start < len(text):
            end = start + max_length
            
            # 尝试在句号处分割
            if end < len(text):
                for i in range(end, start + max_length // 2, -1):
                    if text[i] in ['。', '.', '!', '！', '?', '？']:
                        end = i + 1
                        break
            
            chunk = text[start:end].strip()
            if chunk:
                chunks.append(chunk)
            
            start = end
        
        return chunks


# 创建全局实例
embedding_service = EmbeddingService() 